﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using WeChatApp.Helper;
using System.Data;

namespace WeChatApp.Repositories
{
    public class BaseRepository
    {
        private SqlSugarClient _model = null;
        public SqlSugarClient DBModel
        {
            get {
                if (_model == null)
                {
                    _model = DBHelper.DbModel;
                }
                return _model;
            }
        }
        /// <summary>
        /// 初始化
        /// 尽量接着使用 SetEntitiesModel 设置数据源
        /// </summary>
        public BaseRepository()
        {

        }
        /// <summary>
        /// 设置 数据库操作类
        /// </summary>
        /// <param name="model"></param>
        public void SetEntitiesModel(SqlSugarClient model)
        {
            _model = model;
        }

        public BaseRepository(string connectString)
        {
            _model = new SqlSugarClient(new ConnectionConfig() { ConnectionString = connectString, DbType = SqlSugar.DbType.Oracle, IsAutoCloseConnection = true });
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="model"></param>
        public BaseRepository(SqlSugarClient model)
        {
            SetEntitiesModel(model);
        }


        /// <summary>
        /// 通过 ID 搜索数据库对象
        /// </summary>
        /// <typeparam name="TDBClass">数据表对象</typeparam>
        /// <param name="id">对象ID</param>
        /// <returns>对应ID的对象</returns>
        public virtual TDBClass Get<TDBClass>(string id) where TDBClass : class
        {
            string sql = string.Format("select * from {0} where id=@id", typeof(TDBClass).Name);

            var result = DBModel.Ado.SqlQuery<TDBClass>(sql,
                new SugarParameter("id", id));

            return result.FirstOrDefault();
        }

        public virtual bool Delete<TDBClass>(string id) where TDBClass : class
        {
            string sql = string.Format("delete from {0} where id=@id", typeof(TDBClass).Name);

            var result = DBModel.Ado.ExecuteCommand(sql,
                new SugarParameter("id", id));

            return result > 0;
        }
        public DataTable SqlGetDataTable(string sql)
        {
            return DBModel.Ado.GetDataTable(sql);
        }

    }
}
